# -*- coding: utf-8 -*-
"""
@File    :   views.py
@Time    :   2024/04/12 11:24:15
@Author  :   Ennis.Zhou
@Desc    :   None
"""
import os.path
from flask import session, jsonify, g, request
from werkzeug.datastructures import FileStorage
from flask_restx import Namespace, Resource, reqparse, fields
from werkzeug.utils import secure_filename
from config import BaseConfig

from utils.response_code import RET
from utils.common import create_token, login_required, allowed_file
from apps.models.user import User

from . import user_model

api = Namespace(name="user", description="用户列表")


# 登录
@api.route("/login")
class Login(Resource):
    # 定义restful 风格的方法

    @api.doc(description="访问登录页面")
    def get(self):
        api.logger.info(" 登录系统 -------------")
        return jsonify(code=RET.OK, msg="访问登录页面")

    @api.doc(description="用户登录接口")
    # @api.marshal_list_with(user_model)
    def post(self):
        # 获取前端传过来的参数
        api_data = api.payload
        userna = api_data.get("username")
        phone = api_data.get("phone")
        passwd = api_data.get("password")
        # 校验数据
        if not all([userna, passwd]):
            return jsonify(code=RET.DBERR, msg="用户名和密码不能为空")
        try:
            user = User.query.filter_by(username=userna).first()
        except Exception as e:
            api.logger.info(" 获取信息失败 -------------")
            return jsonify(code=RET.USERERR, msg="获取信息失败")
        # 校验密码
        if user is None:
            return jsonify(code=RET.USERERR, msg="用户不存在或未激活")
        if not user.check_user_pwd(passwd):
            return jsonify(code=RET.PWDERR, msg="密码错误")
        # 创建token
        token = create_token(user.id, phone=user.phone)
        data = {"token": token}
        api.logger.info(data)
        # 创建session
        session["uuid"] = user.id
        # 登录
        return jsonify(code=RET.OK, msg="登录成功", data=data)


# 注册
@api.route("/register")
class Register(Resource):

    @api.doc(description="用户注册接口")
    @api.expect(user_model, validate=True)
    def post(self):
        # 获取所有的接口参数，类型为dict
        raw_data = api.payload
        user = User(raw_data)

        # 校验手机号码唯一性
        flag = user.verification()
        if flag:
            return jsonify(
                code=RET.DATAEXIST,
                message="用户名或手机号已存在",
            )
        user.save_data()
        api.logger.info("注册成功")
        return jsonify(
            code=RET.OK,
            message="注册成功",
        )


# 查询所有用户
@api.route("/getUser")
class GetUserList(Resource):

    @api.doc(description="查询所有用户接口")
    @login_required
    def get(self):
        users = User.query.all()
        list_user = [user.to_user_dict() for user in users]
        api.logger.info("查询成功")
        return jsonify(
            code=RET.OK,
            data=list_user,
            message="查询成功",
        )


# 查询一个用户
@api.route("/get/<string:user_id>")
class GetUserId(Resource):
    @api.doc(description="查询单个用户接口")
    @login_required
    def get(self, user_id):
        user = User.query.filter(User.id == user_id).first()
        print(user)
        if not user:
            return jsonify(code=RET.DATAERR, message="该用户不存在")
        api.logger.info("查询成功")
        return jsonify(
            code=RET.OK,
            data=user.to_user_dict(),
            message="查询成功",
        )


# 修改密码
@api.route("/update/pwd")
class UpdatePassword(Resource):
    @api.doc(description="修改用户密码接口")
    @login_required
    def put(self):
        user = g.user
        user_new = api.payload
        old_password = user_new.get("oldPassword")
        if user_new.get("newPassword") == '':
            return jsonify(code=RET.DATAERR, msg="新密码不得为空")
        if user_new.get("newPassword") != user_new.get("confirmPassword"):
            return jsonify(code=RET.DBERR, msg="两次密码不一样")
        is_right = user.check_user_pwd(old_password)
        if not is_right:
            return jsonify(code=RET.DATAERR, msg="旧密码错误")
        user.password = user_new.get("newPassword")
        user.save_data()
        api.logger.info("修改密码成功")
        return jsonify(
            code=RET.OK,
            message="修改密码成功",
        )


# 重置密码
@api.route("/reset/pwd")
class ResetPassword(Resource):
    @api.doc(description="重置用户密码接口")
    @login_required
    def put(self):
        api_data = api.payload
        u_id = api_data.get("id")
        user = User.query.filter(User.id == u_id).first()
        if not user:
            return jsonify(code=RET.DATAERR, message="该用户不存在")
        user.password = BaseConfig.RESET_PWD
        user.save_data()
        api.logger.info("重置密码成功")
        return jsonify(
            code=RET.OK,
            message="重置密码成功",
        )


# 添加用户
@api.route("/add")
class AddUser(Resource):
    @api.doc(description="添加用户接口")
    @login_required
    def post(self):
        user_d = api.payload
        user = User(user_d)
        # 校验手机号码唯一性
        flag = user.verification()
        if flag:
            return jsonify(
                code=RET.DATAEXIST,
                message="用户名或手机号已存在",
            )
        user.save_data()
        api.logger.info("添加用户成功")
        return jsonify(
            code=RET.OK,
            message="添加用户成功",
        )


# 编辑用户
@api.route("/update/<string:user_id>")
class UpdateUser(Resource):
    @api.doc(description="编辑用户接口")
    @api.expect(user_model, validate=True)
    @login_required
    def put(self, user_id):
        user = User.query.filter(User.id == user_id).first()
        print(user)
        user_d = api.payload
        if not user:
            return jsonify(code=RET.DATAERR, message="该用户不存在")
        else:
            user.nickname = user_d['nickname']
            user.username = user_d['username']
            user.sex = user_d['sex']
            user.phone = user_d['phone']
            user.account_status = user_d['account_status']

        user.update_data()
        api.logger.info("编辑用户成功")
        return jsonify(
            code=RET.OK,
            message="编辑用户成功",
        )


# 删除用户
@api.route("/delete/<string:user_id>")
class DeleteUser(Resource):
    @api.doc(description="删除用户接口")
    @login_required
    def delete(self, user_id):
        user = User.query.filter(User.id == user_id).first()
        print(user)
        if not user:
            return jsonify(code=RET.DATAERR, message="该用户不存在")
        user.delete_data()
        return jsonify(
            code=RET.OK,
            message="删除成功",
        )


# 启用用户
@api.route("/setUserEnable")
class SetEnable(Resource):
    @api.doc(description="启用用户接口")
    @login_required
    def post(self):
        api_data = api.payload
        u_id = api_data.get("id")
        user = User.query.filter(User.id == u_id).first()
        if not user:
            return jsonify(code=RET.DATAERR, message="该用户不存在")
        if user.account_status == 1:
            return jsonify(code=RET.DATAERR, message="用户已是启用状态")
        user.account_status = 1
        api.logger.info("启用用户成功")
        return jsonify(
            code=RET.OK,
            message="启用用户成功",
        )


# 禁用用户
@api.route("/setUserDisable")
class SetDisable(Resource):
    @api.doc(description="禁用用户接口")
    @login_required
    def post(self):
        api_data = api.payload
        u_id = api_data.get("id")
        user = User.query.filter(User.id == u_id).first()
        if not user:
            return jsonify(code=RET.DATAERR, message="该用户不存在")
        if user.account_status == 0:
            return jsonify(code=RET.DATAERR, message="用户已是禁用状态")
        user.account_status = 0
        api.logger.info("禁用用户成功")
        return jsonify(
            code=RET.OK,
            message="禁用用户成功",
        )


# 上传文件
@api.route("/upload_file")
class UploadAvatar(Resource):
    @api.doc(description="上传用户头像功能")
    @login_required
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('file', required=True, type=FileStorage, location='files')
        args = parser.parse_args()
        file = args['file']  # 获取文件对象
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)  # 校验文件名称合法
            file.save(os.path.join(BaseConfig.UPLOAD_FOLDER, filename))
            return jsonify(
                code=RET.OK,
                message="上传成功"
            )
        else:
            return jsonify(
                code=RET.IOERR,
                message="图片[ %s ]格式，不支持上传" % file.filename
            )


# 定义文件模型，支持上传多个文件
gallery_model = api.parser()
gallery_model.add_argument('files', type=fields.List(fields.Raw(type='file')), location='files', required=True,
                           help='Multiple files')


# 上传多个文件
@api.route("/upload/files")
class UploadAvatar(Resource):
    @api.doc(description="上传多个文件功能")
    @api.expect(gallery_model)
    @login_required
    def post(self):
        files = request.files.getlist('files')
        for file in files:
            if file and allowed_file(file.filename):
                # 上传的文件名必须是非中文
                filename = secure_filename(file.filename)
                print(filename)
                file.save(os.path.join(BaseConfig.UPLOAD_FOLDER) + filename)
            else:
                api.logger.info("图片[ %s ]格式，不支持上传" % file.filename)
                return jsonify(
                    code=RET.IOERR,
                    message="图片[ %s ]格式，不支持上传" % file.filename,
                )
        return jsonify(
            code=RET.OK,
            message="上传文件成功",
        )


@api.route('/get_session/')
class GetAndSetSession(Resource):
    @login_required
    def get(self):
        print(g.user)
        # session["uuid"] = str(uuid.uuid4())
        # 获取session
        username = session.get('uuid')  # derek
        return username
